package ajax;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import services.Blogger;
import services.WordPress;

import com.google.gdata.data.Entry;
import com.google.gson.Gson;

import models.Blog;
import models.News;

public class CheckBlog extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("html/plain");
		
		TreeMap results = new TreeMap();
		
		String blogId = (String) request.getParameter("blogId");
		String username = (String) request.getParameter("username");
		String password = (String) request.getParameter("password");
		String type = (String) request.getParameter("type");
		//Set news
		News news = new News();
		news.setTitle("Test blog " + blogId);
		news.setDescription("Test blog with id " + blogId + " and username is " + username);
		
		//Set blog
		Blog blog = new Blog();
		blog.setBlogId(blogId);
		blog.setUsername(username);
		blog.setPassword(password);
		
		if (type != null && type.equalsIgnoreCase("wordpress")) {
			WordPress wp = new WordPress(blog);
			try {
				int id = wp.createPost(news);
				if (id != 0) {
					wp.deletePost(id);
					results.put("success", "true");
					results.put("message", "<b style='color:blue;'>Ok</b>");
				} else {
					results.put("success", "false");
					results.put("message", "<b style='color:red;'>False</b>");
				}
			} catch (Exception e) {
				results.put("success", "false");
				results.put("message", "<b style='color:red;'>False</b>");
			}
		} else {	
			Blogger blogger = new Blogger(blog);
			try {
				Entry entry = blogger.createPost(news);
				blogger.deletePost((String) entry.getEditLink().getHref());
				results.put("success", "true");
				results.put("message", "<b style='color:blue;'>Ok</b>");
			} catch (Exception e) {
				results.put("success", "false");
				results.put("message", "<b style='color:red;'>False</b>");
			}
		}
		
		String json = new Gson().toJson(results);
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json);
	}
}
